package com.hyzh.latte.vehicle.nezha;

import cn.hutool.core.collection.CollectionUtil;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * @author songkui
 * @since 2024/3/21 9:06
 */
public class NezhaSessionManager {

    //key: sessionId;  v：Client
    private final ConcurrentHashMap<String, NezhaClient> clientMap = new ConcurrentHashMap<>();

    // key: parkCode
    private final ConcurrentHashMap<String, ParkClientCamera> clientCameraMap = new ConcurrentHashMap<>();

    private NezhaSessionManager(){}

    private static final class ManagerHolder {
        static final NezhaSessionManager manager = new NezhaSessionManager();
    }
    public static NezhaSessionManager getInstance(){
        return ManagerHolder.manager;
    }



    public void putClient(NezhaClient client){
        clientMap.put(client.getSessionId(), client);
    }


    public NezhaClient getNezhaClient(String sessionId){
        return clientMap.get(sessionId);
    }


    public void removeClient(NezhaClient client, boolean isChannelCols){
        if (isChannelCols){
            clientMap.remove(client.getSessionId());
        }
        ParkClientCamera clientCamera = clientCameraMap.get(client.getParkCode());
        if (null != clientCamera){
            clientCamera.removeCameraMap(client);
        }
    }

    public void switchCamera(NezhaClient client,  Set<String> newCameraCode, boolean isALL){
        getParkClientCamera(client.getParkCode()).switchCamera(client, newCameraCode, isALL);
    }

    private ParkClientCamera getParkClientCamera(String parkCode){
       return clientCameraMap.computeIfAbsent(parkCode, k -> new ParkClientCamera());
    }


    // 通过摄像头获取 能够看到的摄像头的 client
    public Set<NezhaClient> listClientByCameraCode(String parkCode, String cameraCode){

        Set<String> sesssionIdSet = getParkClientCamera(parkCode).listSessionIdByCameraCode(cameraCode);
        if (CollectionUtil.isEmpty(sesssionIdSet)){
            return null;
        }

        return sesssionIdSet.stream().map(clientMap::get).filter(Objects::nonNull).collect(Collectors.toSet());
    }

    public Set<NezhaClient> setClientByParkCode(String parkCode){
        return clientMap.values().stream().filter(c -> parkCode.equals(c.getParkCode())).collect(Collectors.toSet());
    }

    public Collection<NezhaClient> setClientByAll(){
        return clientMap.values();
    }

}
